package eu.scillman.net.tcp;

import java.net.*;

import eu.scillman.net.IClient;
import eu.scillman.net.Member;

/**
 * The client used for theater mode. (Thread-safe)
 * @author Jiri Waning
 */
public class Client implements IClient {	
	/** The thread that is hosting the connection. **/
	private Thread thread;
	
	/** The engine used for communicating to the remote host. **/
	private ClientEngine engine;
	
	/**
	 * Create a new client object that can connect to a remote host.
	 */
	public Client() {
		engine = new ClientEngine();
		thread = new Thread(engine);
	}
	
	/**
	 * Ensures clean up of the used resources.
	 */
	@Override
	public void finalize() throws Throwable {
		disconnect();
		super.finalize();
	}
	
	/**
	 * Connect to a remote host.
	 * @param address The address of the remote host. (IP-address preferred!)
	 * @param port The port of the remote host.
	 */
	public void connect(String address, int port) {
		try {
			if (engine == null) {
				engine.disconnect();
				InetAddress iAddress = InetAddress.getByName(address);
				engine.connect(iAddress, port);
			}
		} catch (UnknownHostException ex) {
			System.out.println("Unknown host!");
		}
	}
	
	/**
	 * Disconnect from the remote host.
	 */
	public void disconnect() {
		if (engine != null) {
			engine.disconnect();
			thread.interrupt();
			engine = null;
		}
	}
	
	/**
	 * Send data to the remote host.
	 * @param data The data that has to be send to the remote host.
	 */
	public void send(String data) {
		
	}
	
	/**
	 * Receive data from the remote host.
	 * @return 
	 */
	public byte[] receive() {
		return null;
	}

	public boolean hold() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void connect(Member remoteDevice) {
		// TODO Auto-generated method stub
		
	}
}
